import {  type Post } from "@prisma/client";
import { prisma } from "@/prisma";

export type PostWithData = Post & {
  topic: { name: string };
  User: { name: string | null };
  _count: { comments: number };
};

export function fetchPostsByTopicName(name: string): Promise<PostWithData[]> {
   return prisma.post.findMany({
    where: {
      topic: {
        name
      }
    },
    include: {
      topic: { select: { name: true } },
      User: { select: { name: true } },
      _count: { select: { comments: true } },
    }
  }) as Promise<PostWithData[]>;
}


/**
 * 获取顶部的帖子
 * @returns 顶部的帖子
 */
export function fetchTopPosts(): Promise<PostWithData[]> {
  return prisma.post.findMany({
    orderBy: [
      {
        comments: {
          _count: "desc",
        },
      },
    ],
    take: 5,
    include: {
      User: {
        select: {
          name: true,
          image: true,
        },
      },
      topic: {
        select: {
          name: true,
        },
      },
      _count: {
        select: {
          comments: true,
        },
      },
    },
  })  as Promise<PostWithData[]>;
}


/**
 * 根据标题或者内容去搜索帖子
 * @param pnameorcon 标题或者内容
 * @returns 帖子列表
 */
export function fetchPostsByPnameorcon(pnameorcon: string): Promise<PostWithData[]> {
  return prisma.post.findMany({
    include: {
      topic: { select: { name: true } },
      User: { select: { name: true, image: true } },
      _count: { select: { comments: true } },
    },
    where: {
      OR: [{ title: { contains: pnameorcon } }, { content: { contains: pnameorcon } }],
    },
  }) as Promise<PostWithData[]>;
}